#include <iostream>
#include <memory>

using std::cout;
using std::endl;
using std::shared_ptr;

//shared_ptr本质上是强引用的智能指针
//每次进行赋值和复制时，count都会+1
class Child;
class Parent{
public:
    Parent(){
        cout<<"Parent()"<<endl;
    }

    ~Parent(){
        cout<<"~Parent()"<<endl;
    }

    shared_ptr<Child> _pChild;
};

class Child{
public:
    Child(){
        cout<<"Child()"<<endl;
    }

    ~Child(){
        cout<<"~Child()"<<endl;
    }

    shared_ptr<Parent> _pParent;    //你包含我我包含你
};

void test(){
    shared_ptr<Parent> spParent(new Parent());  //栈对象
    shared_ptr<Child> spChild(new Child());
    cout<<"spParent.use_count()="<<spParent.use_count()<<endl;
    cout<<"spChild.use_count()="<<spChild.use_count()<<endl;

    cout<<endl;
    spParent->_pChild=spChild;  //赋值
    spChild->_pParent=spParent; 
    cout<<"spParent.use_count()="<<spParent.use_count()<<endl;
    cout<<"spChild.use_count()="<<spChild.use_count()<<endl;
    //此时引用计数变为2，且进程结束后没有析构
    //说明发生了死锁
    //因为单独靠堆空间的自动释放，不能释放它们数据成员里的那俩指针
}

int main()
{   
    test();
    return 0;
}

